package com.wp.rcm.controller;
import com.wp.rcm.pojo.Customer;
import com.wp.rcm.service.CustomerService;
import com.wp.rcm.util.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/crm/customer")
public class CustomerController {

    @Resource
    private CustomerService customerService;


    @RequestMapping("/list")
    public String findAll(Model model, @RequestParam(required = false)String custName,
                          @RequestParam(required = false)String custRegion, Integer currPageNo) {
        Integer page1 = currPageNo == null ? 1 : currPageNo;

        Page page = new Page();
        page.setTotal(customerService.count(custName, custRegion)); // 数据总条数
        if (page1 < 1) {
            page1 = 1;
            model.addAttribute("message", "当前已是最顶一页");
        }
        if (page1 > page.getPages()) {
            page1 = page.getPages();
            model.addAttribute("message", "当前已是最后一页");
        }
        page.setCurrent(page1); // 设置偏移量

        // 存储数据
        List<Customer> all = customerService.findAll(custName, custRegion, page.getOffset(), page.getPageSize());

        page.setList(all);

        model.addAttribute("customerPage", page);


        return "customer/list";
    }

    @GetMapping("/del/{custNo}")
    @ResponseBody
    public Map del(@PathVariable(name = "custNo") String custNo){

        Map<String,Object> map = new HashMap<>();

        int del = customerService.delete(custNo);

        if (del>0){
            map.put("delResult","true");
        }else {
            map.put("delResult","false");
        }
        return map;
    }
}
